﻿using System;
using Microsoft.SharePoint.WebControls;
using System.Collections;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.SharePoint;


namespace CodeArt.SharePoint.Controls
{
    using CodeArt.SharePoint.Configuration;

    class PickerSearchDialog : PickerDialog
    {
        internal PickerSearch Picker
        {
            get { return (PickerSearch)base.EditorControl; }
        }
        public PickerSearchDialog(PickerQueryControlBase query, PickerResultControlBase result, EntityEditorWithPicker editor)
            : base(query, result, editor)
        {
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (base.CustomProperty != null)
            {
                PickerSearch picker =  (PickerSearch)base.EditorControl;
                byte[] buffer = Convert.FromBase64String(CustomProperty);
                using (MemoryStream stream = new MemoryStream(buffer))
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    picker.PickerData = (PickerSearchData)formatter.Deserialize(stream);
                }

            }

            DialogTitle = Picker.PickerData.PickerTemplate.Title;
            Description = Picker.PickerData.PickerTemplate.Description;
        }


          public PickerSearchDialog()
            : base(
                new PickerSearchControl(), 
                new TableResultControl(),
                new PickerSearch())
        {
        }


        protected override void OnPreRender(EventArgs e)
        {            
            TableResultControl resultControl = (TableResultControl)this.ResultControl;

            // Create a display column for each field in the default view

            foreach (ViewFieldElement vfield in this.Picker.PickerData.PickerTemplate.ViewFields.Fields)
            {
                resultControl.ColumnDisplayNames.Add(vfield.Value);
                resultControl.ColumnNames.Add(vfield.Name);

                if (!string.IsNullOrEmpty(vfield.ColumnWidth))
                {
                    try
                    {
                        //resultControl.ColumnWidths.Add(String.Format("{0}%", vfield.ColumnWidth));
                        resultControl.ColumnWidths.Add(vfield.ColumnWidth);
                    }
                    catch
                    {
                        resultControl.ColumnWidths.Add("100px");
                    }
                }
                else
                {
                    resultControl.ColumnWidths.Add("100px");
                }
            }
                        
            base.OnPreRender(e);
        }
    }
}
